import React, { useState, useEffect } from 'react';
import { get } from '../utils/api';
import { useAuth } from '../contexts/AuthContext';
import './Dashboard.css';

interface DashboardStats {
  totalAssets: number;
  totalUsers: number;
  totalValue: number;
  lowStockItems: number;
  recentAssets: Array<{
    id: string;
    name: string;
    category: string;
    status: string;
    createdAt: string;
  }>;
}

const Dashboard: React.FC = () => {
  const { user } = useAuth();
  const [stats, setStats] = useState<DashboardStats>({
    totalAssets: 0,
    totalUsers: 0,
    totalValue: 0,
    lowStockItems: 0,
    recentAssets: []
  });
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState('');

  useEffect(() => {
    fetchDashboardData();
  }, []);

  const fetchDashboardData = async () => {
    try {
      const response = await get('/dashboard/stats');
      if (response.success && response.data) {
        // 确保数据结构正确，提供默认值
        const data = response.data;
        setStats({
          totalAssets: data.totalAssets || 0,
          totalUsers: data.totalUsers || 0,
          totalValue: data.totalValue || 0,
          lowStockItems: data.lowStockItems || 0,
          recentAssets: Array.isArray(data.recentAssets) ? data.recentAssets : []
        });
      } else {
        setError('获取仪表板数据失败');
      }
    } catch (error) {
      console.error('Failed to fetch dashboard data:', error);
      setError('获取仪表板数据失败');
    } finally {
      setLoading(false);
    }
  };

  const formatCurrency = (value: number) => {
    return new Intl.NumberFormat('zh-CN', {
      style: 'currency',
      currency: 'CNY'
    }).format(value);
  };

  const formatDate = (dateString: string) => {
    return new Date(dateString).toLocaleDateString('zh-CN');
  };

  const getStatusColor = (status: string) => {
    switch (status) {
      case 'active':
        return 'success';
      case 'maintenance':
        return 'warning';
      case 'retired':
        return 'danger';
      default:
        return 'secondary';
    }
  };

  const getStatusText = (status: string) => {
    switch (status) {
      case 'active':
        return '使用中';
      case 'maintenance':
        return '维护中';
      case 'retired':
        return '已退役';
      default:
        return status;
    }
  };

  if (loading) {
    return (
      <div className="dashboard-loading">
        <div className="spinner"></div>
        <p>加载仪表板数据...</p>
      </div>
    );
  }

  if (error) {
    return (
      <div className="dashboard-error">
        <div className="error-icon">❌</div>
        <h3>加载失败</h3>
        <p>{error}</p>
        <button onClick={fetchDashboardData} className="btn btn-primary">
          重试
        </button>
      </div>
    );
  }

  return (
    <div className="dashboard">
      <div className="dashboard-header">
        <h1>仪表板</h1>
        <p>欢迎回来，{user?.username}！</p>
      </div>

      {/* 统计卡片 */}
      <div className="stats-grid">
        <div className="stat-card">
          <div className="stat-icon assets">📦</div>
          <div className="stat-content">
            <h3>总资产数</h3>
            <p className="stat-number">{stats.totalAssets}</p>
          </div>
        </div>

        <div className="stat-card">
          <div className="stat-icon users">👥</div>
          <div className="stat-content">
            <h3>用户数</h3>
            <p className="stat-number">{stats.totalUsers}</p>
          </div>
        </div>

        <div className="stat-card">
          <div className="stat-icon value">💰</div>
          <div className="stat-content">
            <h3>总价值</h3>
            <p className="stat-number">{formatCurrency(stats.totalValue)}</p>
          </div>
        </div>

        <div className="stat-card">
          <div className="stat-icon warning">⚠️</div>
          <div className="stat-content">
            <h3>低库存</h3>
            <p className="stat-number">{stats.lowStockItems}</p>
          </div>
        </div>
      </div>

      {/* 快速操作 */}
      <div className="quick-actions">
        <h2>快速操作</h2>
        <div className="action-grid">
          <a href="/assets" className="action-card">
            <div className="action-icon">📋</div>
            <h3>查看资产</h3>
            <p>管理和查看所有资产</p>
          </a>

          <a href="/inventory" className="action-card">
            <div className="action-icon">📊</div>
            <h3>库存管理</h3>
            <p>管理库存和盘点</p>
          </a>

          {user?.role === 'admin' && (
            <a href="/users" className="action-card">
              <div className="action-icon">👤</div>
              <h3>用户管理</h3>
              <p>管理系统用户</p>
            </a>
          )}
        </div>
      </div>

      {/* 最近资产 */}
      <div className="recent-assets">
        <h2>最近添加的资产</h2>
        {stats.recentAssets.length > 0 ? (
          <div className="assets-table">
            <table>
              <thead>
                <tr>
                  <th>资产名称</th>
                  <th>类别</th>
                  <th>状态</th>
                  <th>添加日期</th>
                </tr>
              </thead>
              <tbody>
                {stats.recentAssets.map((asset) => (
                  <tr key={asset.id}>
                    <td className="asset-name">{asset.name}</td>
                    <td className="asset-category">{asset.category}</td>
                    <td>
                      <span className={`status-badge ${getStatusColor(asset.status)}`}>
                        {getStatusText(asset.status)}
                      </span>
                    </td>
                    <td className="asset-date">{formatDate(asset.createdAt)}</td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        ) : (
          <div className="empty-state">
            <div className="empty-icon">📭</div>
            <h3>暂无资产</h3>
            <p>还没有添加任何资产</p>
            <a href="/assets" className="btn btn-primary">
              添加第一个资产
            </a>
          </div>
        )}
      </div>
    </div>
  );
};

export default Dashboard;
